import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import '../services/ai_image_service.dart';
import 'package:flutter/foundation.dart';
import 'package:image_picker/image_picker.dart';

class ImageToImagePage extends StatefulWidget {
  const ImageToImagePage({super.key});

  @override
  State<ImageToImagePage> createState() => _ImageToImagePageState();
}

class _ImageToImagePageState extends State<ImageToImagePage> {
  Uint8List? _sourceBytes;
  bool _generating = false;
  int _modeIndex = 0; // 0: 图生图, 1: 文生图

  final TextEditingController _promptCtrl = TextEditingController();
  final FocusNode _promptFocus = FocusNode();

  // 固定模型：用户指定
  static const String _fixedModel = 'nano-banana';

  // 结果展示
  String? _generatedUrl;
  String? _revisedPrompt;
  String? _errorMsg;

  @override
  void dispose() {
    _promptCtrl.dispose();
    _promptFocus.dispose();
    super.dispose();
  }

  Future<void> _pickImage() async {
    final result = await FilePicker.platform.pickFiles(type: FileType.image, withData: true);
    final file = result?.files.first;
    if (file != null && file.bytes != null) {
      setState(() {
        _sourceBytes = file.bytes;
        _generatedUrl = null;
        _revisedPrompt = null;
        _errorMsg = null;
      });
    }
  }
 
   // 移动端拍照导入参考图（仅 Android/iOS 显示入口）
   Future<void> _captureImage() async {
     try {
       final picker = ImagePicker();
       final XFile? picked = await picker.pickImage(source: ImageSource.camera, imageQuality: 92);
       if (picked != null) {
         final bytes = await picked.readAsBytes();
         setState(() {
           _sourceBytes = bytes;
           _generatedUrl = null;
           _revisedPrompt = null;
           _errorMsg = null;
         });
       }
     } catch (e) {
       setState(() {
         _errorMsg = '拍照失败：$e';
       });
     }
   }

  Future<void> _doGenerate() async {
    final prompt = _promptCtrl.text.trim();
    if (_modeIndex == 1 && prompt.isEmpty) {
      setState(() {
        _errorMsg = '请输入提示词';
      });
      return;
    }
    if (_modeIndex == 0 && _sourceBytes == null) {
      setState(() {
        _errorMsg = '请先选择一张图片';
      });
      return;
    }

    setState(() {
      _generating = true;
      _errorMsg = null;
      _generatedUrl = null;
      _revisedPrompt = null;
    });
    try {
      if (_modeIndex == 1) {
        // 文生图（固定模型）
        final resp = await AiImageService.generateImage(
          GenerationRequest(prompt: prompt, model: _fixedModel),
        );
        if (resp.data.isNotEmpty) {
          setState(() {
            _generatedUrl = resp.data.first.url;
            _revisedPrompt = resp.data.first.revisedPrompt;
          });
        }
      } else {
        // 图生图（固定模型）
        final resp = await AiImageService.editImages(
          EditRequest(prompt: prompt, model: _fixedModel, images: [_sourceBytes!], responseFormat: 'url'),
        );
        if (resp.data.isNotEmpty) {
          setState(() {
            _generatedUrl = resp.data.first.url;
            _revisedPrompt = resp.data.first.revisedPrompt;
          });
        }
      }
    } catch (e) {
      setState(() {
        _errorMsg = e.toString();
      });
    } finally {
      setState(() {
        _generating = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('AI 图像')),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          // 模式切换
          Wrap(spacing: 8, children: [
            ChoiceChip(
              label: const Text('图生图'),
              selected: _modeIndex == 0,
              onSelected: (s) => setState(() => _modeIndex = 0),
            ),
            ChoiceChip(
              label: const Text('文生图'),
              selected: _modeIndex == 1,
              onSelected: (s) => setState(() => _modeIndex = 1),
            ),
          ]),
          const SizedBox(height: 12),

          const SizedBox(height: 12),
          // 顶部参考图预览已移除；参考图预览位于底部结果图上方

          const SizedBox(height: 16),
          // 生成按钮状态：根据模式与输入有效性启用
          Builder(builder: (context) {
            final canGenerate = !_generating && ((_modeIndex == 1 && _promptCtrl.text.trim().isNotEmpty) || (_modeIndex == 0 && _sourceBytes != null));
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 操作区
                Wrap(spacing: 12, runSpacing: -8, children: [
                  if (_modeIndex == 0)
                    ElevatedButton.icon(
                      onPressed: _generating ? null : _pickImage,
                      icon: const Icon(Icons.image),
                      label: const Text('选择图片'),
                    ),
                  if (_modeIndex == 0 && !kIsWeb && (defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.iOS))
                    ElevatedButton.icon(
                      onPressed: _generating ? null : _captureImage,
                      icon: const Icon(Icons.photo_camera),
                      label: const Text('拍照'),
                    ),
                   ElevatedButton.icon(
                     onPressed: canGenerate ? () => _doGenerate() : null,
                     icon: const Icon(Icons.auto_awesome),
                     label: const Text('生成'),
                   ),
                 ]),
              ],
            );
          }),

          const SizedBox(height: 16),
          TextField(
            controller: _promptCtrl,
            focusNode: _promptFocus,
            maxLines: 3,
            decoration: const InputDecoration(
              labelText: '提示词（Prompt）',
              border: OutlineInputBorder(),
              hintText: '描述你希望生成的风格或内容...',
            ),
            onChanged: (_) => setState(() {}),
            onSubmitted: (_) {
              // 文生图：输入完成即生成；图生图：需手动点击“生成”
              if (!_generating && _modeIndex == 1) {
                _doGenerate();
              }
            },
          ),

          const SizedBox(height: 12),
          // 移除模型选择与强度滑块，改为固定模型
          const Text(
            '模型固定：Nano Banana\n文生图：输入完成或点击“生成”。图生图：选择图片后点击“生成”。',
            style: TextStyle(color: Colors.grey),
          ),

          const SizedBox(height: 16),
          // 参考图预览（图生图）放到底部并位于结果图上方
          if (_modeIndex == 0) ...[
            _PreviewBox(
              title: '参考图',
              child: _sourceBytes == null
                  ? _EmptyPreviewTip(text: '请选择一张图片')
                  : ClipRRect(
                      borderRadius: BorderRadius.circular(12),
                      child: Image.memory(_sourceBytes!, fit: BoxFit.contain),
                    ),
            ),
            const SizedBox(height: 16),
          ],

           const SizedBox(height: 16),
           // 生成结果展示移动到最下面，并在生成时显示loading
           _PreviewBox(
             title: '生成结果',
             child: _generating
               ? const Center(child: CircularProgressIndicator())
                : (_generatedUrl != null
                    ? ClipRRect(
                        borderRadius: BorderRadius.circular(12),
                        child: Image.network(
                          _generatedUrl!,
                          fit: BoxFit.cover,
                          errorBuilder: (c, e, s) => Container(
                            color: Colors.grey.shade200,
                            child: const Icon(Icons.broken_image),
                          ),
                        ),
                      )
                    : _EmptyPreviewTip(text: '生成后将在此处显示结果')),
           ),
          if (_revisedPrompt != null) ...[
            const SizedBox(height: 8),
            Text('修正后的提示词：$_revisedPrompt', style: const TextStyle(color: Colors.grey)),
          ],
          if (_errorMsg != null) ...[
            const SizedBox(height: 8),
            Text(_errorMsg!, style: const TextStyle(color: Colors.red)),
          ],
        ],
      ),
    );
  }
}

class _EmptyPreviewTip extends StatelessWidget {
  final String text;
  const _EmptyPreviewTip({required this.text});
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Icon(Icons.image_outlined, size: 48),
          const SizedBox(height: 8),
          Text(text),
        ],
      ),
    );
  }
}

class _PreviewBox extends StatelessWidget {
  final String title;
  final Widget child;
  const _PreviewBox({required this.title, required this.child});

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(title, style: Theme.of(context).textTheme.titleMedium),
        const SizedBox(height: 8),
        AspectRatio(
          aspectRatio: 16 / 9,
          child: DecoratedBox(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              color: Colors.grey.shade200,
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(12),
              child: child,
            ),
          ),
        ),
      ],
    );
  }
}